<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2019/5/13
 * Time: 5:11 PM
 */

namespace App\Api\Controllers\Member;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\OrderController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Common\PaySuccessAction;
use App\Models\MemberCzList;
use App\Models\MemberJf;
use App\Models\MemberList;
use App\Models\MemberSetJf;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class PayController extends BaseController
{
    //商家充值-c扫b
    public function cz(Request $request)
    {
        try {
            $user = $this->parseToken(); //
            $store_id = $request->get('store_id');
            $cz_s_money = $request->get('cz_s');
            $cz_money = $request->get('cz');
            $open_id = $request->get('open_id');
            $mb_id_c = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $mb_id = $request->get('mb_id', '');
            $mb_id = $mb_id == "NULL" || $mb_id == "" ? $mb_id_c : $mb_id;
            $ways_type = $request->get('ways_type');
            $cz_trade_no = 'CZ' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $merchant_id = $request->get('merchant_id', '0');

            $check_data = [
                'store_id' => '门店ID',
                'cz_s' => '充值送金额',
                'cz' => '充值金额',
                'open_id' => '支付宝微信标示',
                'ways_type' => '通道类型',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select("status",'config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close')
                ->first();
            if (!$store) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有关联认证门店请联系服务商'
                ]);
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户已经被服务商关闭'
                ]);
            }
            if($store->status!=1){
                return json_encode([
                    'status' => '2',
                    'message' => '商户已经被服务商关闭,请联系客服'
                ]);
            }


            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $where = [];
            $obj_ways = new  PayWaysController();
            $ways = $obj_ways->ways_type($ways_type, $store_id, $store_pid);
            if (!$ways) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有开通此类型通道'
                ]);
            }
            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                return json_encode([
                    'status' => 2,
                    'message' => $error
                ]);
            }

            $ways_source = $ways->ways_source;
            $ways_type = $ways->ways_type;
            $ways_source_desc = $ways->ways_source;
            $company = $ways->company;
            $rate = $ways->rate;
            $fee_amount = $ways->rate * $cz_money / 100;
            $ali_user_id = "";
            $wx_openid = "";
            if ($ways_source == "alipay") {
                $ali_user_id = $open_id;
                $where[] = ['ali_user_id', '=', $open_id];
            }

            if ($ways_source == "weixin") {
                $wx_openid = $open_id;
                $where[] = ['wx_openid', '=', $open_id];
            }

            $MemberList = MemberList::where('store_id', $store_id)
                ->where('mb_id', $mb_id)
                ->where($where)
                ->select('mb_phone', 'mb_money')
                ->first();

            //不是会员
            $mb_phone = "";
            $mb_money = "";
            if (!$MemberList) {
                //积分赠送情况
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->first();

                $new_mb_jf = 0;
                if ($MemberSetJf) {
                    $new_mb_jf = $MemberSetJf->new_mb_s_jf;
                }

                $in_sert_data = [
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'config_id' => $config_id,
                    'mb_id' => $mb_id,
                    'mb_status' => '1',
                    'mb_ver' => '1',
                    'mb_ver_desc' => '普通会员',
                    'mb_name' => "未设置",
                    'mb_phone' => "未绑定",
                    'mb_nick_name' => "未设置",
                    'mb_logo' => url('/member/mrtx.png'),
                    'mb_jf' => $new_mb_jf,
                    'mb_money' => '0.00', //储值金额
                    'mb_time' => date('Y-m-d H:i:s', time()),
                    'pay_counts' => 1,
                    'pay_moneys' => $cz_money,
                    'wx_openid' => $wx_openid,
                    'ali_user_id' => $ali_user_id,
                ];
                MemberList::create($in_sert_data);
            } else {
                $mb_phone = $MemberList->mb_phone;
                $mb_money = $MemberList->mb_money;
            }

            $data = [
                'merchant_name' => '会员充值',
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'store_pid' => $store_pid,
                'tg_user_id' => $tg_user_id,
                'total_amount' => $cz_money,
                'shop_price' => $cz_money,
                'remark' => '会员充值',
                'device_id' => 'member_cz',
                'shop_name' => '会员充值',
                'shop_desc' => '会员充值',
                'open_id' => $open_id,
                'ways_type' => $ways_type,
                'other_no' => $cz_trade_no,
                'notify_url' => '',
            ];
            $obj = new PayBaseController();
            $re = $obj->qr_auth_pay_public($data, $ways);
            $re_arr = json_decode($re, true);
            $out_trade_no = isset($re_arr['out_trade_no']) ? $re_arr['out_trade_no'] : "";

            //充值入库
            if ($re_arr['status'] == 1) {
                $inser_data = [
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'ways_source_desc' => $ways_source_desc,
                    'ways_source' => $ways_source,
                    'company' => $company,
                    'rate' => $rate,
                    'cz_money' => $cz_money,//'充值支付金额',
                    'cz_s_money' => $cz_s_money,//'充值送金额',
                    'pay_status' => 2,
                    'pay_time' => '',
                    'cz_type' => $cz_s_money > 0 ? 2 : 1,
                    'cz_type_desc' => $cz_s_money > 0 ? '充值送' : '普通充值',
                    'total_amount' => $cz_money,//'订单总金额',
                    'fee_amount' => $fee_amount,//'手续费',
                    'receipt_amount' => $cz_money - $fee_amount,//'商家实收',
                    'out_trade_no' => $cz_trade_no,
                    'mb_id' => $mb_id,//会员ID
                    'mb_phone' => $mb_phone,//会员手机号
                ];
                MemberCzList::create($inser_data);
            }
            $re_arr['mb_money'] = $mb_money;

            return json_encode($re_arr);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //商家充值-b扫c
    public function cz_b(Request $request)
    {
        try {
            $user = $this->parseToken(); //
            $store_id = $request->get('store_id');
            $cz_s_money = $request->get('cz_s');
            $cz_money = $request->get('cz');
            $device_id = $request->get('device_id');
            $mb_id_c = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $mb_id = $request->get('mb_id', $mb_id_c);
            $mb_id = (($mb_id == "NULL") || ($mb_id == "")) ? $mb_id_c : $mb_id;
            $ways_source = $request->get('ways_source', 'alipay');
            $cz_trade_no = 'CZ' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $merchant_id = $request->get('merchant_id', '');
            $code = $request->get('code');
            $remark = $request->get('remark', '');
            $ali_user_id = $request->get('ali_user_id', '');
            $wx_openid = $request->get('wx_openid', '');
            $cz_s_money = number_format($cz_s_money, 2, '.', '');
            $cz_money = number_format($cz_money, 2, '.', '');

            $check_data = [
                'store_id' => '门店ID',
                'merchant_id' => "收银员ID",
                'cz_s' => '充值送金额',
                'cz' => '充值金额',
                'code' => '支付授权码',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            if ($ali_user_id == "" && $wx_openid == "") {
                return json_encode([
                    'status' => 2,
                    'message' => '用户id不能为空'
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select("status",'config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close')
                ->first();
            if (!$store) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有关联认证门店请联系服务商'
                ]);
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户已经被服务商关闭'
                ]);
            }

            if($store->status!=1){
                return json_encode([
                    'status' => '2',
                    'message' => '商户已经被服务商关闭,请联系客服'
                ]);
            }


            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $where = [];
            $obj_ways = new  PayWaysController();
            $ways = $obj_ways->ways_source($ways_source, $store_id, $store_pid);
            if (!$ways) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有开通此类型通道'
                ]);
            }
            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                return json_encode([
                    'status' => 2,
                    'message' => $error
                ]);
            }
            $ways_source = $ways->ways_source;
            $ways_type = $ways->ways_type;
            $ways_source_desc = $ways->ways_source;
            $company = $ways->company;
            $rate = $ways->rate;
            $fee_amount = $ways->rate * $cz_money / 100;

            $MemberList = MemberList::where('store_id', $store_id)
                ->where('mb_id', $mb_id)
                ->select('mb_phone', 'mb_money')
                ->first();

            //不是会员
            $mb_phone = "";
            $mb_money = 0;
            if (!$MemberList) {
                //积分赠送情况
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->first();

                $new_mb_jf = 0;
                if ($MemberSetJf) {
                    $new_mb_jf = $MemberSetJf->new_mb_s_jf;
                }

                $in_sert_data = [
                    'store_id' => $store_id,
                    'merchant_id' => $merchant_id,
                    'config_id' => $config_id,
                    'mb_id' => $mb_id,
                    'mb_status' => '1',
                    'mb_ver' => '1',
                    'mb_ver_desc' => '普通会员',
                    'mb_name' => "未设置",
                    'mb_phone' => "未绑定",
                    'mb_nick_name' => "未设置",
                    'mb_logo' => url('/member/mrtx.png'),
                    'mb_jf' => $new_mb_jf,
                    'mb_money' => '0.00', //储值金额
                    'mb_time' => date('Y-m-d H:i:s', time()),
                    'pay_counts' => 1,
                    'pay_moneys' => $cz_money,
                    'wx_openid' => $wx_openid,
                    'ali_user_id' => $ali_user_id,
                ];
                MemberList::create($in_sert_data);
            } else {
                $mb_phone = $MemberList->mb_phone;
                $mb_money = $MemberList->mb_money;
            }

            $inser_data = [
                'store_id' => $store_id,
                'store_name' => $store_name,
                'ways_source_desc' => $ways_source_desc,
                'ways_source' => $ways_source,
                'company' => $company,
                'rate' => $rate,
                'cz_money' => $cz_money, //'充值支付金额',
                'cz_s_money' => $cz_s_money, //'充值送金额',
                'pay_status' => 2,
                'pay_time' => '',
                'cz_type' => $cz_s_money > 0 ? 2 : 1,
                'cz_type_desc' => $cz_s_money > 0 ? '充值送' : '普通充值',
                'total_amount' => $cz_money, //'订单总金额',
                'fee_amount' => $fee_amount, //'手续费',
                'receipt_amount' => $cz_money - $fee_amount, //'商家实收',
                'out_trade_no' => $cz_trade_no,
                'mb_id' => $mb_id, //会员ID
                'mb_phone' => $mb_phone, //会员手机号
            ];
            MemberCzList::create($inser_data);

            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'code' => $code,
                'total_amount' => $cz_money,
                'shop_price' => $cz_money,
                'remark' => $remark,
                'device_id' => 'member_cz',
                'shop_name' => '充值' . $cz_money,
                'shop_desc' => '充值',
                'store_id' => $store_id,
                'other_no' => $cz_trade_no,
            ];
            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->scan_pay_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'status' => 2,
                    'message' => $tra_data_arr['message'],
                ];
                return json_encode($err);
            }

            $tra_data_arr['data']['mb_id'] = $mb_id;

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                $tra_data_arr['data']['mb_money'] = "" . ($mb_money + $cz_s_money + $cz_money) . "";

                return json_encode($tra_data_arr);
            } elseif ($tra_data_arr['pay_status'] == '2') {
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
            } else {

            }

            return json_encode($tra_data_arr);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }


    //会员卡支付 c扫b
    public function qr_pay_submit(Request $request)
    {
        try {
            $store_id = $request->get('store_id');
            $merchant_id = $request->get('merchant_id', '0');
            $total_amount = $request->get('total_amount');
            $total_amount = number_format($total_amount, 2, '.', '');
            $pay_amount = $request->get('pay_amount');
            $pay_amount = number_format($pay_amount, 2, '.', '');
            $is_jf_dk = $request->get('is_jf_dk', '2');
            $dk_jf = $request->get('dk_jf', 0);
            $dk_money = $request->get('dk_money', 0);
            $is_member_pay = $request->get('is_member_pay', '2');
            $remark = $request->get('remark');
            $open_id = $request->get('open_id');
            $mb_id = $request->get('mb_id');
            $ways_type = $request->get('ways_type');

            $check_data = [
                'store_id' => '门店ID',
                'open_id' => '支付宝微信标示',
                'ways_type' => '通道类型',
                'total_amount' => "订单金额",
                'pay_amount' => "付款金额",
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select("status",'config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close')
                ->first();
            if (!$store) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有关联认证门店请联系服务商'
                ]);
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户已经被服务商关闭'
                ]);
            }

            if($store->status!=1){
                return json_encode([
                    'status' => '2',
                    'message' => '商户已经被服务商关闭,请联系客服'
                ]);
            }

            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $where = [];
            $obj_ways = new  PayWaysController();
            $ways = $obj_ways->ways_type($ways_type, $store_id, $store_pid);
            if (!$ways) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有开通此类型通道'
                ]);
            }
            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                return json_encode([
                    'status' => 2,
                    'message' => $error
                ]);
            }

            $ways_source = $ways->ways_source;
            $ways_type = $ways->ways_type;
            $ways_source_desc = $ways->ways_source;
            $company = $ways->company;
            $rate = $ways->rate;
            $fee_amount = $ways->rate * $pay_amount / 100;
            $out_trade_no = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $MemberList = "";

            //默认最终抵扣金额为0
            $end_dk_money = '0.00';
            $end_dk_jf = "0";
            //如果有积分抵扣查看会员和积分信息
            if ($is_jf_dk == '1') {
                $MemberList = MemberList::where('store_id', $store_id)
                    ->where('mb_id', $mb_id)
                    ->where($where)
                    ->first();
                if (!$MemberList) {
                    return json_encode([
                        'status' => 2,
                        'message' => '会员ID不存在'
                    ]);
                }

                //会员的积分和余额
                $mb_jf = $MemberList->mb_jf; //用户积分
                $mb_money = $MemberList->mb_money;


                //1.查看门店的积分规则
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->select('dk_jf_m', 'dk_rmb')
                    ->first();
                if (!$MemberSetJf) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商家未设置积分抵扣'
                    ]);
                }

                $dk_rmb = $MemberSetJf->dk_rmb;
                $dk_jf_m = $MemberSetJf->dk_jf_m;

                //3.用户的积分一共可以抵扣多少钱
                $jf_dk_money = ($mb_jf / $MemberSetJf->dk_jf_m) * $MemberSetJf->dk_rmb;
                $jf_dk_money = number_format($jf_dk_money, 2, '.', '');

                $dk_money = number_format($dk_money, 2, '.', '');

                //如果前端的参数和后端参数不匹配无法抵扣
                if ($dk_money != $jf_dk_money) {
                    return json_encode([
                        'status' => 2,
                        'message' => '抵扣金额数字有误！请刷新再试'
                    ]);
                }
                //如果前端的参数和后端参数不匹配无法抵扣
                if ($mb_jf != $dk_jf) {
                    return json_encode([
                        'status' => 2,
                        'message' => '抵扣积分数字有误！请刷新再试'
                    ]);
                }

                //如果积分抵扣的钱大于等于支付金额 代表全部是积分支付
                if ($total_amount <= $jf_dk_money) {
                    //多了的钱
                    $dl_monery = $jf_dk_money - $total_amount;
                    //多了的积分
                    $dl_jf = ($dl_monery / $dk_rmb) * $dk_jf_m;
                    $dk_jf = $dk_jf - $dl_jf;
                    $dk_money = $total_amount;

                }

                $end_dk_money = $dk_money;//最终算下来抵扣的钱
                $end_dk_jf = $dk_jf;//最终算下来抵扣的积分

                $insert['dk_jf'] = $end_dk_jf;
                $insert['dk_money'] = $end_dk_money;
                $M_INERT['mb_jf'] = $mb_jf - $end_dk_jf;

            }

            if ($total_amount != $pay_amount + $end_dk_money) {
                return json_encode([
                    'status' => 2,
                    'message' => '交易金额不等于付款金额+积分抵扣金额'
                ]);
            }

            //会员卡支付
            if ($is_member_pay == '1') {
                if ($ways_source == "alipay") {
                    $where[] = ['ali_user_id', '=', $open_id];
                } else {
                    $where[] = ['wx_openid', '=', $open_id];
                }

                if (!$MemberList) {
                    $MemberList = MemberList::where('store_id', $store_id)
                        ->where('mb_id', $mb_id)
                        ->where($where)
                        ->first();

                    if (!$MemberList) {
                        return json_encode([
                            'status' => 2,
                            'message' => '会员ID不存在'
                        ]);
                    }
                    //会员的积分和余额
                    $mb_jf = $MemberList->mb_jf;//用户积分
                    $mb_money = $MemberList->mb_money;

                }
                //创建订单
                $insert = [
                    'config_id' => $config_id,
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $out_trade_no,
                    'store_id' => $store_id,
                    'store_name' => $store_name,
                    'merchant_id' => $merchant_id,
                    'merchant_name' => '',
                    'is_settlement_user' => 1,
                    'user_id' => $tg_user_id,
                    'payment_method' => 'member',//支付方式
                    'ways_type' => '18888',
                    'ways_type_desc' => '会员卡支付',
                    'ways_source' => 'member',
                    'ways_source_desc' => '会员卡支付',
                    'company' => 'member',//通道方
                    'total_amount' => $total_amount,
                    'shop_price' => $total_amount,
                    'receipt_amount' => '0.00',//商家实际收到的款项
                    'pay_amount' => '0.00',//用户需要支付总金额
                    'buyer_pay_amount' => '0.00',//用户实际付款支付金额
                    'status' => 1,
                    'pay_status' => '1',//系统状态
                    'pay_status_desc' => "会员卡支付成功",
                    'rate' => '0',//商户交易时的费率
                    'fee_amount' => '0',
                    "remark" => $remark,
                    'member_money' => $pay_amount,//会员支付
                    'pay_time' => date('Y-m-d H:i:s', time()),//支付时间
                ];

                //积分抵扣
                if ($is_jf_dk == "1") {
                    //会员卡余额+抵扣的金额必须大于付款金额
                    if (($mb_money + $end_dk_money) < $pay_amount) {
                        return json_encode([
                            'status' => 2,
                            'message' => '会员卡余额不足'
                        ]);
                    }

                } else {
                    //会员卡余额必须大于付款金额
                    if ($mb_money < $pay_amount || $mb_money < 0.01) {
                        return json_encode([
                            'status' => 2,
                            'message' => '会员卡余额不足'
                        ]);
                    }
                }

                $up_mb_money = $mb_money - $pay_amount;
                $M_INERT['mb_money'] = $up_mb_money;

                //返回的信息
                $re = [
                    'status' => 1,
                    'message' => '支付成功',
                    'is_member_pay' => $is_member_pay,
                    'pay_amount' => $pay_amount,
                    'end_dk_money' => $end_dk_money,
                    'end_dk_jf' => $end_dk_jf,
                ];

            } else {

                //带有金额带支付
                if ($pay_amount > 0) {
                    //正常扫码交易
                    $data = [
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'config_id' => $config_id,
                        'store_name' => $store_name,
                        'store_pid' => $store_pid,
                        'tg_user_id' => $tg_user_id,
                        'total_amount' => $total_amount,
                        'shop_price' => $total_amount,
                        'remark' => $remark,
                        'device_id' => 'web',
                        'shop_name' => '扫码支付',
                        'shop_desc' => '扫码支付',
                        'open_id' => $open_id,
                        'ways_type' => $ways_type,
                        'other_no' => '',
                        'notify_url' => '',
                        'pay_amount' => $pay_amount,
                        'dk_jf' => $dk_jf,
                        'dk_money' => $dk_money,
                    ];

                    $obj = new PayBaseController();
                    $return_json = $obj->qr_auth_pay_public($data, $ways);
                    $re = json_decode($return_json, true);

                    if ($re['status'] == 2) {
                        return $return_json;
                    }
                    $re['is_member_pay'] = $is_member_pay;
                    $re['pay_amount'] = $pay_amount;
                    $re['end_dk_money'] = $end_dk_money;
                    $re['end_dk_jf'] = $end_dk_jf;
                } else {
                    //没有金额带支付
                    $re['status'] = 1;
                    $re['message'] = '积分支付成功';
                    $re['is_member_pay'] = $is_member_pay;
                    $re['pay_amount'] = $pay_amount;
                    $re['end_dk_money'] = $end_dk_money;
                    $re['end_dk_jf'] = $end_dk_jf;
                }
            }

            //更新数据库
            //开启事务
            try {
                DB::beginTransaction();

                //如果有会员卡
                if ($is_member_pay == '1') {
                    //1.入库订单
                    $insert_re =  $this->insert_day_order($insert);
                }

                //如果有积分抵扣
                if ($is_jf_dk == "1" || $is_member_pay == '1') {
                    //2更新会员卡数据
                    $MemberList->update($M_INERT);
                    $MemberList->save();
                }

                DB::commit();
            } catch (\Exception $e) {
                Log::info($e);
                DB::rollBack();
                return json_encode(['status' => 2, 'message' => $e->getMessage()]);
            }

            //会员卡支付成功
            if ($is_member_pay == '1') {
                //支付成功后的动作
                $data = [
                    'ways_type' => '18888',
                    'ways_type_desc' => '会员卡支付',
                    'ways_source' => 'member',
                    'ways_source_desc' => '会员卡支付',
                    'company' => 'member',//通道方
                    'source_type' => '18888',//返佣来源
                    'source_desc' => '会员卡支付',//返佣来源说明
                    'total_amount' => $total_amount,
                    'out_trade_no' => $out_trade_no,
                    'rate' => 0,
                    'merchant_id' => $merchant_id,
                    'store_id' => $store_id,
                    'user_id' => $tg_user_id,
                    'config_id' => $config_id,
                    'store_name' => $store_name,
                    'pay_time' => date('Y-m-d H:i:s', time()),
                    'no_user_money' => '1',
                    'fee_amount' => 0.00,
                ];

                PaySuccessAction::action($data);
            }
            // 积分记录入库
            if ($is_jf_dk == "1" && $end_dk_jf > 0) {
                //
                $insert_data = [
                    'store_id' => $store_id,
                    'mb_id' => $mb_id,
                    'jf' => $end_dk_jf,
                    'jf_desc' => '积分抵扣',
                    'type' => '101',
                    'type_desc' => "积分抵扣",

                ];
                MemberJf::create($insert_data);
            }

            return json_encode($re);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    //会员卡支付 b扫c
    public function member_pay_submit(Request $request)
    {
        try {
            $store_id = $request->get('store_id');
            $merchant_id = $request->get('merchant_id', '0');
            $total_amount = $request->get('total_amount');
            $total_amount = number_format($total_amount, 2, '.', '');
            $pay_amount = $request->get('pay_amount');
            if (isset($pay_amount)) $pay_amount = number_format($pay_amount, 2, '.', '');
            $is_jf_dk = $request->get('is_jf_dk', '2');
            $dk_jf = $request->get('dk_jf', 0);
            $dk_money = $request->get('dk_money', 0);
            $remark = $request->get('remark');
            $open_id = $request->get('open_id');
            $mb_id = $request->get('mb_id');
            $is_member_pay = '1';
//            Log::info('会员卡支付b_2_c: ');
//            Log::info($is_jf_dk);

            $check_data = [
                'store_id' => '门店ID',
                'open_id' => '支付宝微信标示',
                'total_amount' => "订单金额",
                'pay_amount' => "付款金额",
                'mb_id' => '会员卡ID'
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            $store = Store::where('store_id', $store_id)
                ->select("status",'config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close')
                ->first();
            if (!$store) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有关联认证门店请联系服务商'
                ]);
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户已经被服务商关闭'
                ]);
            }


            if($store->status!=1){
                return json_encode([
                    'status' => '2',
                    'message' => '商户已经被服务商关闭,请联系客服'
                ]);
            }

            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $out_trade_no = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            $MemberList = "";

            //默认最终抵扣金额为0
            $end_dk_money = '0.00';
            $end_dk_jf = "0";

            $MemberList = MemberList::where('store_id', $store_id)
                ->where('mb_id', $mb_id)
                ->first();
            if (!$MemberList) {
                return json_encode([
                    'status' => 2,
                    'message' => '会员ID不存在'
                ]);
            }

            //会员的积分和余额
            $mb_jf = $MemberList->mb_jf; //用户积分
            $mb_money = $MemberList->mb_money;
            $mb_name = $MemberList->mb_name;
            $mb_phone = $MemberList->mb_phone;

            //如果有积分抵扣查看会员和积分信息
            if ($is_jf_dk == '1') {
                //1.查看门店的积分规则
                $MemberSetJf = MemberSetJf::where('store_id', $store_id)
                    ->select('dk_jf_m', 'dk_rmb')
                    ->first();
                if (!$MemberSetJf) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商家未设置积分抵扣'
                    ]);
                }

                $dk_rmb = $MemberSetJf->dk_rmb;
                $dk_jf_m = $MemberSetJf->dk_jf_m;

                //3.用户的积分一共可以抵扣多少钱
                $jf_dk_money = ($mb_jf / $MemberSetJf->dk_jf_m) * $MemberSetJf->dk_rmb;
                $jf_dk_money = number_format($jf_dk_money, 2, '.', '');
                $dk_money = number_format($dk_money, 2, '.', '');

                //如果前端的参数和后端参数不匹配无法抵扣
                if ($dk_money != $jf_dk_money) {
                    return json_encode([
                        'status' => 2,
                        'message' => '抵扣金额数字有误！请刷新再试'
                    ]);
                }
                //如果前端的参数和后端参数不匹配无法抵扣
                if ($mb_jf != $dk_jf) {
                    return json_encode([
                        'status' => 2,
                        'message' => '抵扣积分数字有误！请刷新再试'
                    ]);
                }

                //如果积分抵扣的钱大于等于支付金额 代表全部是积分支付
                if ($total_amount <= $jf_dk_money) {
                    //多了的钱
                    $dl_monery = $jf_dk_money - $total_amount;
                    //多了的积分
                    $dl_jf = ($dl_monery / $dk_rmb) * $dk_jf_m;
                    $dk_jf = $dk_jf - $dl_jf;
                    $dk_money = $total_amount;

                }

                $end_dk_money = $dk_money;//最终算下来抵扣的钱
                $end_dk_jf = $dk_jf;//最终算下来抵扣的积分

                $insert['dk_jf'] = $end_dk_jf;
                $insert['dk_money'] = $end_dk_money;
                $M_INERT['mb_jf'] = $mb_jf - $end_dk_jf;
            }

            if ($total_amount != $pay_amount + $end_dk_money) {
                return json_encode([
                    'status' => 2,
                    'message' => '交易金额不等于付款金额+积分抵扣金额'
                ]);
            }

            //创建订单
            $insert = [
                'config_id' => $config_id,
                'out_trade_no' => $out_trade_no,
                'trade_no' => $out_trade_no,
                'store_id' => $store_id,
                'store_name' => $store_name,
                'merchant_id' => $merchant_id,
                'merchant_name' => '',
                'is_settlement_user' => 1,
                'user_id' => $tg_user_id,
                'payment_method' => 'member', //支付方式
                'ways_type' => '18888',
                'ways_type_desc' => '会员卡支付',
                'ways_source' => 'member',
                'ways_source_desc' => '会员卡支付',
                'company' => 'member', //通道方
                'total_amount' => $total_amount,
                'shop_price' => $total_amount,
                'receipt_amount' => '0.00', //商家实际收到的款项
                'pay_amount' => '0.00', //用户需要支付总金额
                'buyer_pay_amount' => '0.00', //用户实际付款支付金额
                'buyer_id' => $open_id, //买家支付宝或者微信id
                'status' => 1,
                'pay_status' => '1', //系统状态
                'pay_status_desc' => "会员卡支付成功",
                'rate' => '0', //商户交易时的费率
                'fee_amount' => '0',
                "remark" => $remark,
                'member_money' => $pay_amount, //会员支付
                'pay_time' => date('Y-m-d H:i:s', time()), //支付时间
            ];

            //积分抵扣
            if ($is_jf_dk == "1") {
                //会员卡余额+抵扣的金额必须大于付款金额
                if (($mb_money + $end_dk_money) < $pay_amount) {
                    return json_encode([
                        'status' => 2,
                        'message' => '会员卡余额不足'
                    ]);
                }
            } else {
                //会员卡余额必须大于付款金额
                if ($mb_money < $pay_amount || $mb_money < 0.01) {
                    return json_encode([
                        'status' => 2,
                        'message' => '会员卡余额不足'
                    ]);
                }
            }

            $up_mb_money = $mb_money - $pay_amount;
            $M_INERT['mb_money'] = $up_mb_money;

            //更新数据库

            //开启事务
            try {
                DB::beginTransaction();

                //如果有会员卡
                if ($is_member_pay == '1') {
                    //1.入库订单
                    $insert_re = $this->insert_day_order($insert);
                }

                //如果有积分抵扣
                if ($is_jf_dk == "1" || $is_member_pay == '1') {
                    //2更新会员卡数据
                    $MemberList->update($M_INERT);
                    $MemberList->save();
                }

                DB::commit();
            } catch (\Exception $e) {
                Log::info($e);
                DB::rollBack();
                return json_encode(['status' => 2, 'message' => $e->getMessage()]);
            }

            $pay_time = date('Y-m-d H:i:s', time());
            //会员卡支付成功
            if ($is_member_pay == '1') {
                //支付成功后的动作
                $data = [
                    'ways_type' => '18888',
                    'ways_type_desc' => '会员卡支付',
                    'ways_source' => 'member',
                    'ways_source_desc' => '会员卡支付',
                    'company' => 'member',//通道方
                    'source_type' => '18888',//返佣来源
                    'source_desc' => '会员卡支付',//返佣来源说明
                    'total_amount' => $total_amount,
                    'out_trade_no' => $out_trade_no,
                    'rate' => 0,
                    'merchant_id' => $merchant_id,
                    'store_id' => $store_id,
                    'user_id' => $tg_user_id,
                    'config_id' => $config_id,
                    'store_name' => $store_name,
                    'pay_time' => $pay_time,
                    'no_user_money' => '1',
                    'fee_amount' => 0.00,
                ];

                PaySuccessAction::action($data);
            }
            // 积分记录入库
            if ($is_jf_dk == "1" && $end_dk_jf > 0) {
                //
                $insert_data = [
                    'store_id' => $store_id,
                    'mb_id' => $mb_id,
                    'jf' => $end_dk_jf,
                    'jf_desc' => '积分抵扣',
                    'type' => '101',
                    'type_desc' => "积分抵扣",
                ];

                MemberJf::create($insert_data);
            }

            //返回的信息
            $re = [
                'status' => 1,
                'message' => '支付成功',
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'mb_name' => $mb_name,
                    'mb_phone' => $mb_phone,
                    'is_member_pay' => $is_member_pay,
                    'pay_amount' => $pay_amount,
                    'total_amount' => $total_amount,
                    'end_dk_money' => $end_dk_money,
                    'end_dk_jf' => $end_dk_jf,
                    'pay_time' => $pay_time,
                    'mb_id' => $mb_id
                ]
            ];

            return json_encode($re);
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }


    //查询订单号状态
    public function order_foreach(Request $request)
    {
        //获取请求参数
        try {
            $store_id = $request->get('store_id', '');
            $out_trade_no = $request->get('out_trade_no', '');
            $ways_type = $request->get('ways_type', '');
            $config_id = $request->get('config_id', '');

            $data = [
                'out_trade_no' => $out_trade_no,
                'store_id' => $store_id,
                'ways_type' => $ways_type,
                'config_id' => $config_id,
            ];
            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($data);
            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                return $return;
            }

            $mb_id = "";
            $mb_money = "";

            //用户支付成功 附带会员信息
            if ($tra_data_arr['pay_status'] == '1') {
                $MemberCzList = MemberCzList::where('out_trade_no', $tra_data_arr['data']['other_no'])
                    ->select('cz_money', 'cz_s_money', 'mb_id')
                    ->first();
                if ($MemberCzList) {
                    $mb_id = $MemberCzList->mb_id;
                    $MemberList = MemberList::where('mb_id', $mb_id)
                        ->select('mb_money')
                        ->first();
                    if ($MemberList) {
                        $mb_money = $MemberList->mb_money + $MemberCzList->cz_s_money + $MemberCzList->cz_money;
                        $mb_money = number_format($mb_money, 2, '.', '');
                    }
                }
                $tra_data_arr['data']['mb_id'] = $mb_id;
                $tra_data_arr['data']['mb_money'] = $mb_money;
            }

            return json_encode($tra_data_arr);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage() . $exception->getLine();
            return $this->format();
        }
    }


}
